<template>
  <!-- 分页控制器 -->
  <div class="page-control">
    <!-- 左侧 -->
    <div class="left">
      <span>第 {{ page }} / {{ validPageCount }} 页</span>
      <span>共 {{ sum }} 个</span>
    </div>
    <!-- 右侧 -->
    <div class="right">
      <!-- 如果当前页大于1，显示上一页按钮 -->
      <div class="prev" @click="$emit('pageChangeHandler', page - 1)" v-show="page > 1">&lt;</div>
      <ul class="page">
        <!-- 当前页大于3,显示省略号 -->
        <span v-show="page > 3">...</span>
        <!-- 如果当前页大于2,显示page-2 -->
        <li v-show="page > 2" @click="$emit('pageChangeHandler', page - 2)">{{ page - 2 }}</li>
        <!-- 如果当前页大于1,显示page-1 -->
        <li v-show="page > 1" @click="$emit('pageChangeHandler', page - 1)">{{ page - 1 }}</li>
        <!-- 当前页 -->
        <li class="active">{{ page }}</li>
        <!-- 如果当前页小于总页数,显示page+1 -->
        <li v-show="validPageCount - page > 0" @click="$emit('pageChangeHandler', page + 1)">{{ page + 1 }}</li>
        <!-- 如果当前页小于总页数减1,显示page+2 -->
        <li v-show="validPageCount - page > 1" @click="$emit('pageChangeHandler', page + 2)">{{ page + 2 }}</li>
        <!-- 当前页小于总页数减2,显示省略号 -->
        <span v-show="validPageCount - page > 2">...</span>
      </ul>
      <!-- 如果当前页小于总页数,显示下一页按钮 -->
      <div class="next" @click="$emit('pageChangeHandler', page + 1)" v-show="validPageCount - page > 0">&gt;</div>
    </div>
  </div>

</template>

<script setup>
import { computed } from 'vue';

// sum: 总数, pageSize: 每页显示个数, page: 当前页
const { sum, pageSize } = defineProps(['sum', 'pageSize', 'page'])
// 总页数
const validPageCount = computed(() => {
  if (pageSize === 0) {
    return 1; // 当pageSize为0时，默认显示1页
  }
  const count = Math.ceil(sum / pageSize);
  return Math.max(count, 1); // 确保返回值最小为1，避免出现小于1的不合理情况
});
</script>

<style lang="scss" scoped>
// 分页控制器
.page-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  background-color: rgba($color: #eee, $alpha: .8);
  margin: .3333rem auto;
  border-bottom: .0167rem solid #ccc;
  padding: 0 .3333rem;
  width: 100%;
  height: .8333rem;
  font-size: .2667rem;

  // 左侧
  .left {
    display: flex;
    align-items: center;

    span {
      margin-right: .1667rem;
    }
  }

  // 右侧
  .right {
    display: flex;
    align-items: center;

    // 上一页和下一页按钮
    .prev,
    .next {
      border: 1px solid #ccc;
      width: 30px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      cursor: pointer;
    }

    // 页码
    .page {
      display: flex;
      margin: .1667rem;

      span,
      li {
        padding: 0 .1667rem;
        height: .5rem;
        line-height: .5rem;
        cursor: pointer;
      }

      span {
        cursor: default;
      }

      .active {
        background-color: #666;
        color: #fff;
      }

      li:hover {
        background-color: #999;
        color: #fff;
      }
    }
  }
}
</style>